package kau.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import kau.dao.BoardDAOImpl;
import kau.dao.ReplyDAOImpl;
import kau.dao.WritingDAOImpl;
import kau.vo.Reply;
import kau.vo.Writing;

import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

public class WritingAction extends MultiActionController {

	@Override
	public void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws ServletException {
		binder.registerCustomEditor(byte[].class,
				new ByteArrayMultipartFileEditor());
		// System.out.println("initBinder");
	}

	public ModelAndView list(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage = new ModelAndView();
		// ArrayList writingList=WritingDAOImpl.getInstance().getAllWritings(1);
		// System.out.println(writingList.size());
		// request.setAttribute("bNumber", 1);
		// System.out.println("enter list");
		int bNumber = Integer.parseInt(request.getParameter("bNumber"));
		int page = 1;
		int limit = 10;

		int listcount = WritingDAOImpl.getInstance().getListCount(bNumber);
		if (request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}

		int maxpage = (int) ((double) listcount / limit + 0.95);
		int startpage = (((int) ((double) page / 10 + 0.9)) - 1) * 10 + 1;
		int endpage = maxpage;

		System.out.println(listcount + " " + endpage);

		String title = BoardDAOImpl.getInstance().getBoard(bNumber).getTitle();
		int writingPermission = BoardDAOImpl.getInstance().getBoard(bNumber)
				.getWritingPermission();

		ArrayList writingList = WritingDAOImpl.getInstance().getPageWritings(
				bNumber, page, limit);

		ArrayList replyCountList = new ArrayList();
		for (int i = 0; i < writingList.size(); i++) {
			replyCountList.add(ReplyDAOImpl.getInstance().getReplyCount(
					((Writing) writingList.get(i)).getwNumber()));

		}

		request.setAttribute("writingList", writingList);
		request.setAttribute("replyCountList", replyCountList);

		request.setAttribute("page", page);
		request.setAttribute("maxpage", maxpage);
		request.setAttribute("startpage", startpage);
		request.setAttribute("endpage", endpage);
		request.setAttribute("listcount", listcount);
		request.setAttribute("boardlist", writingList);

		request.setAttribute("bNumber", bNumber);
		request.setAttribute("title", title);
		request.setAttribute("writingPermission", writingPermission);

		String courseId = null;
		courseId = request.getParameter("courseId");

		// System.out.println("list courseId:" +courseId);
		if (courseId != null && !courseId.equals("")) {
			nextPage.setViewName("/course/index.jsp?content=/course/writing/list.jsp?courseId="
					+ courseId);
			
			System.out.println("courseId");
		} else {
			nextPage.setViewName("index.jsp?content=/writing/list.jsp");
		}
		return nextPage;
	}

	public ModelAndView searchList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage = new ModelAndView();

		int bNumber = Integer.parseInt(request.getParameter("bNumber"));
		int page = 1;
		int limit = 10;
		if (request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}

		String searchWord = request.getParameter("searchWord");
		int listcount = 0;
		int searchIndex = Integer.parseInt(request.getParameter("searchIndex"));
		ArrayList writingList = null;
		if (searchIndex == 1) {

			writingList = WritingDAOImpl.getInstance().getSearchWriting(
					bNumber, page, limit, searchWord, searchIndex);
			listcount = WritingDAOImpl.getInstance()
					.custNameSearch(searchWord, bNumber).size();

		} else if (searchIndex == 2) {
			writingList = WritingDAOImpl.getInstance().getSearchWriting(
					bNumber, page, limit, searchWord, searchIndex);
			listcount = WritingDAOImpl.getInstance()
					.titleSearch(searchWord, bNumber).size();

		} else if (searchIndex == 3) {
			writingList = WritingDAOImpl.getInstance().getSearchWriting(
					bNumber, page, limit, searchWord, searchIndex);
			listcount = WritingDAOImpl.getInstance()
					.contentSearch(searchWord, bNumber).size();

		}

		ArrayList replyCountList = new ArrayList();
		for (int i = 0; i < writingList.size(); i++) {
			replyCountList.add(ReplyDAOImpl.getInstance().getReplyCount(
					((Writing) writingList.get(i)).getwNumber()));

		}

		int maxpage = (int) ((double) listcount / limit + 0.95);
		int startpage = (((int) ((double) page / 10 + 0.9)) - 1) * 10 + 1;
		int endpage = maxpage;

		String title = BoardDAOImpl.getInstance().getBoard(bNumber).getTitle();
		int writingPermission = BoardDAOImpl.getInstance().getBoard(bNumber)
				.getWritingPermission();

		request.setAttribute("writingList", writingList);
		request.setAttribute("replyCountList", replyCountList);

		request.setAttribute("page", page);
		request.setAttribute("maxpage", maxpage);
		request.setAttribute("startpage", startpage);
		request.setAttribute("endpage", endpage);
		request.setAttribute("listcount", listcount);
		request.setAttribute("boardlist", writingList);

		request.setAttribute("bNumber", bNumber);
		request.setAttribute("title", title);
		request.setAttribute("writingPermission", writingPermission);
		// ////////////////////
		request.setAttribute("searchIndex", searchIndex);

		String courseId = null;
		courseId = request.getParameter("courseId");

		if (courseId != null && !courseId.equals("")) {
			nextPage.setViewName("/course/index.jsp?content=/course/writing/list.jsp?courseId="
					+ courseId);
		} else {
			nextPage.setViewName("index.jsp?content=writing/list.jsp");
		}

		return nextPage;
	}

	public ModelAndView writeView(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// System.out.println("write entered!!!");
		ModelAndView nextPage = new ModelAndView();

		String courseId = null;
		// System.out.println("writeView");
		courseId = request.getParameter("courseId");
		
		System.out.println("write view:"+courseId);
		if (courseId != null && !courseId.equals("")) {
			nextPage.setViewName("/course/index.jsp?content=/course/writing/write.jsp&courseId="
					+ courseId);
		} else {
			nextPage.setViewName("index.jsp?content=writing/write.jsp");
		}

		return nextPage;
	}

	public ModelAndView write(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// writing session 이용해서 추후에 다시 코딩
		ModelAndView nextPage = new ModelAndView();

		MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest) request;

		int bNumber = Integer.parseInt(mpRequest.getParameter("bNumber"));
		int wNumber = WritingDAOImpl.getInstance().getMaxwNumber() + 1;

		String title = mpRequest.getParameter("title");
		String contents = request.getParameter("contents");

		MultipartFile file = mpRequest.getFile("uploadFile");

		// File d = new File(,"" + wNumber);
		// d.mkdir();

		String filePath = "";
		String realPath = "";
		String fileName = "";
		if (!file.isEmpty()) {

			filePath = "C:\\upload\\" + request.getContextPath().substring(1);

			File f = new File(filePath, "" + wNumber);
			f.mkdirs();

			realPath = f.getPath();
			fileName = file.getOriginalFilename();
			// System.out.println("fileName: " + fileName);

			// System.out.println("filePath :" + filePath);
			// System.out.println("realPath :"+realPath);
			// file write
			BufferedInputStream reader = null;
			BufferedOutputStream writer = null;
			byte[] buffer = new byte[512];
			int charsRead = 0;
			try {
				reader = new BufferedInputStream(file.getInputStream());
				writer = new BufferedOutputStream(new FileOutputStream(
						new File(realPath, fileName)));
				while ((charsRead = reader.read(buffer)) != -1) {
					// write the buffer out to the output file
					writer.write(buffer, 0, charsRead);
				}

			} catch (IOException e) {
				System.out.println("File Write Error!!" + e);
				e.printStackTrace();
			} finally {
				try {
					if (reader != null)
						reader.close();
					if (writer != null)
						writer.close();
				} catch (IOException e) {
					System.out.println("IO Close Error!!");
				}
			}
		}
		HttpSession session = request.getSession();
		String custId = (String) session.getAttribute("custId");
		String custName = (String) session.getAttribute("custName");

		String today = getToday();

		// System.out.println(title + content);
		Writing writing = new Writing();
		writing.setwNumber(wNumber);
		writing.setbNumber(bNumber);
		writing.setCustId(custId);
		writing.setTitle(title);
		writing.setContent(contents);
		writing.setHits(0);
		writing.setPassword(0);// 왜필요할까???
		writing.setWriteTime(today);
		writing.setIsPublic(1);
		writing.setCategory(1);
		if (!file.isEmpty()) {
			writing.setFilePath(realPath + "\\" + fileName);
		} else {
			writing.setFilePath("");
		}
		// 나중에 다시 해줘야됨
		writing.setWriter(custName);

		WritingDAOImpl.getInstance().insert(writing);
		// nextPage.setViewName("index.jsp");
		nextPage.setViewName("list.writing?bNumber=" + bNumber);

		return nextPage;
	}

	public ModelAndView showWriting(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage = new ModelAndView();
		// System.out.println("showWriting");

		int wNumber = Integer.parseInt(request.getParameter("wNumber"));
		int bNumber = Integer.parseInt(request.getParameter("bNumber"));

		WritingDAOImpl.getInstance().hitsUp(wNumber);
		Writing writing = WritingDAOImpl.getInstance().getWriting(wNumber);
		// System.out.println(writing);
		ArrayList<Reply> replyList = ReplyDAOImpl.getInstance().getAllReplies(
				wNumber);
		//System.out.println(replyList);

		request.setAttribute("writing", writing);
		request.setAttribute("bNumber", bNumber);
		request.setAttribute("replyList", replyList);
		
		
		//System.out.println("showWriting :"+writing);
		
		if(writing.getFilePath()!=null && writing.getFilePath().endsWith("")){
		String fileName;
		String[] temp=writing.getFilePath().split("\\\\");
		int index=temp.length;
		fileName=temp[index-1];
		request.setAttribute("fileName", fileName);
		}
		
		
		

		String courseId = null;
		courseId = request.getParameter("courseId");
			
		 
		if (courseId != null && !courseId.equals("")) {
			System.out.println("courseId :"+courseId);
			nextPage.setViewName("/course/index.jsp?content=/course/writing/view.jsp&courseId="
					+ request.getParameter("courseId"));
		} else {
			nextPage.setViewName("index.jsp?content=writing/view.jsp");

		}

		return nextPage;
	}

	public ModelAndView updateView(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage = new ModelAndView();

		int wNumber = Integer.parseInt(request.getParameter("wNumber"));
		int bNumber = Integer.parseInt(request.getParameter("bNumber"));
		// System.out.println("updateView bnum " + bNumber);

		Writing writing = WritingDAOImpl.getInstance().getWriting(wNumber);
		request.setAttribute("writing", writing);
		request.setAttribute("bNumber", bNumber);

		String courseId = null;
		courseId = request.getParameter("courseId");

		// System.out.println(" updateView courseId :"+courseId);

		if (courseId != null && !courseId.equals("")) {
			nextPage.setViewName("/course/index.jsp?content=/writing/modify.jsp&courseId="
					+ request.getParameter("courseId"));
		} else {
			nextPage.setViewName("index.jsp?content=writing/modify.jsp");
		}
		return nextPage;
	}

	public ModelAndView updateWriting(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage = new ModelAndView();

		int wNumber = Integer.parseInt(request.getParameter("wNumber"));
		int bNumber = Integer.parseInt(request.getParameter("bNumber"));
		// System.out.println("updateWriting bnum " + bNumber);

		String title = request.getParameter("title");
		String contents = request.getParameter("contents");

		Writing writing = WritingDAOImpl.getInstance().getWriting(wNumber);

		// Writing writing = new Writing();
		writing.setTitle(title);
		writing.setContent(contents);
		if (writing.getFilePath() == null) {
			writing.setFilePath("");
		}

		// System.out.println(writing);

		WritingDAOImpl.getInstance().update(writing);

		// System.out.println("updateWriting coruseId: "+request.getParameter("courseId"));

		nextPage.setViewName("list.writing?bNumber=" + bNumber + "&courseId="
				+ request.getParameter("courseId"));
		return nextPage;
	}

	public ModelAndView deleteWriting(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage = new ModelAndView();

		int wNumber = Integer.parseInt(request.getParameter("wNumber"));
		int bNumber = Integer.parseInt(request.getParameter("bNumber"));

		nextPage.setViewName("list.writing?bNumber=" + bNumber + "&courseId="
				+ request.getParameter("courseId"));
		WritingDAOImpl.getInstance().delete(wNumber);

		return nextPage;
	}

	public ModelAndView fileDownload(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage = new ModelAndView();
		// nextPage.setViewName("writing/list.jsp");

		/*
		 * String filePath=new
		 * String(request.getParameter("filePath").getBytes("utf-8"
		 * ),"iso-8859-1"); String[] temp = filePath.split("\\\\"); String
		 * fileName=temp[temp.length-1]; File file=new File(filePath);
		 * 
		 * 
		 * response.reset();
		 * response.setContentType("application/octet-stream");
		 * response.setHeader("Content-Disposition",
		 * "attachment; filename=\""+fileName+"\"" );
		 * response.setHeader("Content-Transfer-Encoding", "binary");
		 * response.setContentLength((int) file.length());
		 * response.setHeader("Pragma","no-cache;");
		 * response.setHeader("Expires","-1;");
		 * 
		 * 
		 * OutputStream out=response.getOutputStream(); FileInputStream in=null;
		 * 
		 * in=new FileInputStream(file); byte[] data=new byte[8906]; int len=-1;
		 * while((len=in.read(data))!=-1){ out.write(data,0,len); }
		 * 
		 * 
		 * System.out.println(filePath);
		 */

		return nextPage;
	}

	public ModelAndView rWrite(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage = new ModelAndView();

		int rNumber = ReplyDAOImpl.getInstance().getMaxrNumber();
		int wNumber = Integer.parseInt(request.getParameter("wNumber"));
		int bNumber = Integer.parseInt(request.getParameter("bNumber"));

		String rContent = request.getParameter("rContent");
		String custId = (String) request.getSession(false).getAttribute(
				"custId");
		String writer = (String) request.getSession(false).getAttribute(
				"custName");

		Writing writing = WritingDAOImpl.getInstance().getWriting(wNumber);
		request.setAttribute("writing", writing);

		Reply reply = new Reply();
		reply.setrNumber(rNumber);
		reply.setContent(rContent);
		reply.setCustId(custId);
		reply.setWriter(writer);
		reply.setwNumber(wNumber);
		reply.setWriteTime(getToday());

		ReplyDAOImpl.getInstance().insert(reply);

		String courseId = null;
		courseId = request.getParameter("courseId");

		nextPage.setViewName("showWriting.writing?wNumber=" + wNumber
				+ "&bNumber=" + bNumber + "&courseId=" + courseId);
		return nextPage;
	}

	public ModelAndView rUpdate(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage = new ModelAndView();
		// nextPage.setViewName("writing/modify.jsp");

		int rNumber = Integer.parseInt(request.getParameter("rNumber"));
		int wNumber = Integer.parseInt(request.getParameter("wNumber"));
		int bNumber = Integer.parseInt(request.getParameter("bNumber"));
		String rContent = request.getParameter("rContent");

		ReplyDAOImpl.getInstance().update(rNumber, rContent);

		String courseId = null;
		courseId = request.getParameter("courseId");
		nextPage.setViewName("showWriting.writing?wNumber=" + wNumber
				+ "&bNumber=" + bNumber + "&courseId=" + courseId);

		return nextPage;
	}

	public ModelAndView rDelete(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage = new ModelAndView();
		nextPage.setViewName("writing/view.jsp");

		int rNumber = Integer.parseInt(request.getParameter("rNumber"));
		int wNumber = Integer.parseInt(request.getParameter("wNumber"));
		int bNumber = Integer.parseInt(request.getParameter("bNumber"));

		// Writing writing = WritingDAOImpl.getInstance().getWriting(wNumber);
		// request.setAttribute("writing", writing);

		ReplyDAOImpl.getInstance().delete(rNumber);
		String courseId = null;
		courseId = request.getParameter("courseId");

		nextPage.setViewName("showWriting.writing?wNumber=" + wNumber
				+ "&bNumber=" + bNumber + "&courseId=" + courseId);
		return nextPage;
	}

	private String getToday() {
		java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
				"yyyy-MM-dd");
		Date d = new Date();
		String sdate = format.format(d);
		// System.out.println(sdate);
		return sdate;
	}
}
